package cn.accjiyun.dao.impl;

import cn.accjiyun.core.dao.DaoSupport;
import cn.accjiyun.core.entity.PageModel;
import cn.accjiyun.dao.LoginLogDao;
import cn.accjiyun.model.article.QueryArticle;
import cn.accjiyun.model.system.LoginLog;
import org.springframework.stereotype.Repository;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/4/25.
 */
@Repository("loginLogDaoImpl")
public class LoginLogDaoImpl extends DaoSupport<LoginLog> implements LoginLogDao{
    /**
     * 添加登录日志
     *
     * @param loginLog
     * @return
     */
    @Override
    public int createLoginLog(LoginLog loginLog) {
        save(loginLog);
        return loginLog.getLoginId();
    }

    /**
     * 分页查询登录日志
     *
     * @param query
     * @param model
     * @return
     */
    @Override
    public List<LoginLog> queryLoginLogPage(QueryArticle query, PageModel<LoginLog> model) {
        Timestamp beginCreateTime = query.getBeginCreateTime() == null ?
                null : new Timestamp(query.getBeginCreateTime().getTime());
        Timestamp endCreateTime = query.getEndCreateTime() == null ?
                null : new Timestamp(query.getEndCreateTime().getTime());
        String where = new StringBuffer().append("where 1=1")
                .append(beginCreateTime == null ? "" : " and loginTime >= ?")
                .append(endCreateTime == null ? "" : " and loginTime <= ?").toString();
        Object[] params = {beginCreateTime, endCreateTime};
        Map<String, String> orderBy = new HashMap<>();
        orderBy.put("loginTime", "desc");
        PageModel<LoginLog> result;
        if (beginCreateTime == null && endCreateTime == null) {
            result = find(model.getPageNo(), model.getPageSize(), orderBy);
        } else {
            result = find(where, params, orderBy, model.getPageNo(), model.getPageSize());
        }
        model.setTotalRecords(result.getTotalRecords());
        model.setTotalPageSize(result.getTotalPageSize());
        return result.getList();
    }
}
